package com.gitee.yusugar.pay.alipay.core;

import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayObject;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.gitee.yusugar.common.pojo.DataRes;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AlipayAppService extends AlipayService {

    @Override
    public DataRes<String> tradePay( AlipayObject model, String notifyUrl, String returnUrl ) {
        AlipayClient alipayClient = super.alipayConfig.buildAlipayClient();

        AlipayTradeAppPayRequest appPayRequest = new AlipayTradeAppPayRequest();
        appPayRequest.setNotifyUrl( StrUtil.isBlank( notifyUrl ) ? super.alipayConfig.getNotifyUrl() : notifyUrl );
        appPayRequest.setReturnUrl( StrUtil.isBlank( returnUrl ) ? super.alipayConfig.getReturnUrl() : returnUrl );

        appPayRequest.setBizModel( model );
        try {
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute( appPayRequest );

            if ( response.isSuccess() )
                return DataRes.data( response.getBody() );

            return errorOrderNoRecord( response, response.getOutTradeNo(), "订单支付异常" );
        } catch ( AlipayApiException e ) {
            return errorRecord( e, "订单支付异常" );
        }
    }
}
